<template>
  <div>
    <el-card>
      <el-form
        ref="form"
        :inline="true"
        :model="filterParams"
        class="demo-form-inline">
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="filterParams.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="注册时间" prop="rangeDate">
          <el-date-picker
            v-model="filterParams.rangeDate"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button
            :disabled="isLoading"
            @click="handleQuery"
            type="primary"
          >查询</el-button>
          <el-button
            @click="handleReset"
          >重置</el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="userInfo"
        style="width: 100%">
        <el-table-column
          prop="id"
          label="用户ID"
          width="180">
        </el-table-column>
        <el-table-column
          label="头像"
          width="180">
          <template slot-scope="scope">
            <img width="30" :src="scope.row.portrait ||'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'">
          </template>
        </el-table-column>
        <el-table-column
          prop="name"
          label="用户名">
        </el-table-column>
        <el-table-column
          prop="phone"
          label="手机号">
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="注册时间">
        </el-table-column>
        <el-table-column
          label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              active-value="ENABLE"
              inactive-value="DISABLE"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="handleForbidUser(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column
          label="操作">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="allocRoles(scope.row)"
            >分配角色</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="filterParams.currentPage"
        :page-sizes="[10, 15, 20]"
        :page-size="filterParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :disabled="isLoading">
      </el-pagination>
      <!-- 分配角色弹框 -->
      <el-dialog
        title="角色分配"
        :visible.sync="dialogVisible"
        width="30%">
        <el-select placeholder="请选择" v-model="roleIdList" multiple>
          <el-option
            v-for="item in allRoleList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="handleAllocUserRole">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { getUserPages, forbidUser } from '@/services/user'
import { getAllRoles, allocUserRole, getUserRole } from '@/services/role'
export default {
  name: 'UserList',
  data () {
    return {
      filterParams: {
        phone: '',
        currentPage: 1,
        pageSize: 10,
        rangeDate: [],
        startCreateTime: '',
        endCreateTime: ''
      },
      total: 0,
      userInfo: [],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      isLoading: false,
      dialogVisible: false,
      // 所有角色
      allRoleList: [],
      // 分配角色时选中的值
      roleIdList: [],
      userId: ''
    }
  },
  created () {
    this.loadUsersInfo()
  },
  methods: {
    async loadUsersInfo () {
      this.isLoading = true
      const { rangeDate } = this.filterParams
      if (rangeDate && rangeDate.length) {
        this.filterParams.startCreateTime = rangeDate[0]
        this.filterParams.endCreateTime = rangeDate[1]
      } else {
        this.filterParams.startCreateTime = ''
        this.filterParams.endCreateTime = ''
      }
      const { data } = await getUserPages(this.filterParams)
      if (data.code === '000000') {
        this.isLoading = false
        this.userInfo = data.data.records
        this.total = data.data.total
      }
    },
    async handleForbidUser (row) {
      const { data } = await forbidUser(row.id)
      console.log(data)
    },
    handleSizeChange (val) {
      // 页面条数发生改变
      this.filterParams.sizePage = val
      // 页面条数发生改变时，需要将当前也还原为初始 1
      this.filterParams.currentPage = 1
      // 页面条数改变，请求接口
      this.loadUsersInfo()
    },
    handleCurrentChange (val) {
      // 当前页发生改变时，将 val 赋值给 current
      this.filterParams.currentPage = val
      // 当前页发生改变，请求接口
      this.loadUsersInfo()
    },
    // 查询用户
    handleQuery () {
      this.filterParams.currentPage = 1
      this.loadUsersInfo()
    },
    // 清空搜索条件
    handleReset () {
      this.$refs.form.resetFields()
      this.loadUsersInfo()
    },
    // 分配角色
    async allocRoles (row) {
      this.dialogVisible = true
      // 将当前用户 ID 保存，以便提交的时候使用
      this.userId = row.id
      const { data } = await getAllRoles()
      if (data.code === '000000') {
        this.allRoleList = data.data
      }
      // 点击分配角色的时候获取当前用户拥有的角色
      const { data: data2 } = await getUserRole(this.userId)
      if (data2.code === '000000') {
        this.roleIdList = data2.data.map(item => item.id)
      }
    },
    async handleAllocUserRole () {
      // this.dialogVisible = false
      const { data } = await allocUserRole({
        userId: this.userId,
        roleIdList: this.roleIdList
      })
      if (data.code === '000000') {
        this.dialogVisible = false
        this.$message.success('角色分配成功！')
      }
    }
  }
}

</script>
<style lang='scss' scoped>
</style>
